package com.xiaofei.threadpool;

import java.util.List;
import java.util.Vector;

public class ThreadPool {
	private boolean isShutDown;
	private List<PThread> idlePool;
	private int threadCounter;
	public synchronized void execute(Runnable target){
		if(isShutDown){
			return;
		}
		PThread thread = null;
		if(idlePool.size()>0){
			thread = idlePool.get(idlePool.size()-1);
			idlePool.remove(thread);
			thread.setTarget(target);
		}else{
			thread = new PThread(target,this,"PThread#"+threadCounter);
			thread.start();
			threadCounter++;
		}
	}
	
	public synchronized void shutdown(){
		for(int i=0;i<idlePool.size();i++){
			idlePool.get(i).shutdown();
		}
		this.idlePool.clear();
		this.isShutDown = true;
	}
	public int getThreadCount(){
		return this.threadCounter;
	}
	
	protected synchronized void rePool(PThread thread){
		if(!isShutDown){
			idlePool.add(thread);
		}
		//如果线程池关闭，则在线程运行结束时关闭线程
		else{
			thread.shutdown();
		}
	}
	
	private ThreadPool(){
		this.idlePool = new Vector<>();
		this.threadCounter = 0;
	}
	private static class SingletonHolder{
		public static final ThreadPool INSTANCE = new ThreadPool();
	}
	public static ThreadPool getInstance(){
		return SingletonHolder.INSTANCE;
	}
}
